package zero_os

import (
	"fmt"
	"github.com/shirou/gopsutil/v3/cpu"
	"github.com/shirou/gopsutil/v3/disk"
	"github.com/shirou/gopsutil/v3/mem"
	"github.com/shirou/gopsutil/v3/net"
	"go.uber.org/zap"
	"os_client/logger"
	"strconv"
	"time"
)

var (
	GetCpu   float64
	GetMem   map[string]uint64
	SentNum  float64
	RecvNum  float64
	DeskInit map[string]interface{}
	DeskInfo []interface{}
)

// CpuInfo cpu监听信息
func CpuInfo() {
	for {
		info, err := cpu.Percent(time.Second*2, false)
		if err != nil {
			logger.Logger.Error("获取cpu信息错误", zap.Error(err))
		}
		GetCpu = info[0]
	}
}

// MemInfo 获取内存信息
func MemInfo() {
	for {
		memory, _ := mem.VirtualMemory()
		GetMem = make(map[string]uint64)
		GetMem["total"] = memory.Total
		GetMem["available"] = memory.Available
		GetMem["used"] = memory.Used
		time.Sleep(time.Second)
	}
}

// GetNetInfo 获取网络信息
func GetNetInfo() {
	var tmpSent uint64
	var tmpRecv uint64
	for {
		info, _ := net.IOCounters(false)
		if tmpSent == 0 || tmpRecv == 0 {
			tmpSent = info[0].BytesSent
			tmpRecv = info[0].BytesRecv
			continue
		} else {
			sentInfo := info[0].BytesSent - tmpSent
			recvInfo := info[0].BytesRecv - tmpRecv
			SentNum = getBytes(sentInfo)
			RecvNum = getBytes(recvInfo)
			tmpSent = info[0].BytesSent
			tmpRecv = info[0].BytesRecv
		}
		time.Sleep(time.Second)
	}
}

//计算网络速率：bytes
func getBytes(num uint64) float64 {
	floatnum := float64(int(num)) / 1024
	value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", floatnum), 64)
	return value
}

// GetDeskInfo 获取磁盘信息
func GetDeskInfo() {
	for {
		info, err := disk.Partitions(true)
		if err != nil {
			logger.Logger.Error("获取磁盘信息错误", zap.Error(err))
		}
		DeskInfo = nil
		for _, part := range info {
			DeskInit = make(map[string]interface{})
			diskInfo, _ := disk.Usage(part.Mountpoint)
			usedDeskInfo, freeDeskInfo := getDeskGB(diskInfo.Used, diskInfo.Free)
			DeskInit["part"] = part.Device
			DeskInit["used"] = usedDeskInfo
			DeskInit["free"] = freeDeskInfo
			DeskInfo = append(DeskInfo, DeskInit)
		}
		time.Sleep(time.Second * 30)
	}
}

//计算磁盘信息：GB
func getDeskGB(UsedPercent uint64, free uint64) (float64, float64) {
	usedConNum := float64(int(UsedPercent)) / 1024 / 1024 / 1024
	usedCon, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", usedConNum), 64)
	freeNum := float64(int(free)) / 1024 / 1024 / 1024
	freeCon, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", freeNum), 64)
	return usedCon, freeCon
}
